package com.qingxin.sys.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * @author Administrator
 *
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {
	
	
	/**
	 * md5加密
	 * 
	 * @param s
	 *            待加密字符串
	 * @return 加密后的字符串
	 */
	public static final String md5(final String s) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String h = Integer.toHexString(0xFF & messageDigest[i]);
				if(h.length() < 2){
					hexString.append("0");
				}
				hexString.append(h);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	
	/**
	 * 获取一个新的UUID字符串，不包括分隔符
	 * 
	 * @return
	 */
	public static String UUID(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	
	
	
	/**
	 * 编码XML特殊字符
	 * 
	 * @param string
	 * @return
	 */
	public static String encodeXml(String xmlString) {
		if(isEmpty(xmlString)){
			return xmlString;
		}
		StringBuffer buffer = new StringBuffer();
		Matcher m = Pattern.compile("[<>'\"&]").matcher(xmlString);
		while(m.find()){
			String ch = m.group();
			switch (ch) {
			case "<":
				m.appendReplacement(buffer, "&lt;");
				break;
			case ">":
				m.appendReplacement(buffer, "&gt;");
				break;
			case "'":
				m.appendReplacement(buffer, "&apos;");
				break;
			case "\"":
				m.appendReplacement(buffer, "&quot;");
				break;
			case "&":
				m.appendReplacement(buffer, "&amp;");
				break;
			}
		}
		m.appendTail(buffer);
		//清除不可见字符
		return buffer.toString().replaceAll("[\u0000-\u0008\u000b-\u000c\u000e-\u001f]", "");
	}
	
	
	
	
	/**
	 * 获取数据库Varchar字段长度，其中一个非ASCII字符算两个长度
	 * @param string
	 * @param length
	 * @return
	 */
	public static String getLengthVarchar(String string, int length){
		if(string==null){
			return null;
		}
		if(string.length()<= (length>>2)){
			return string;
		}
		int len = 0;
		StringBuilder buf = new StringBuilder();
		for(int i=0, n=string.length(); i<n; i++){
			int c = string.charAt(i);
			len++;
			if(c>127){
				len++;
			}
			if(len > length){
				break;
			}
			buf.append((char)c);
		}
		return buf.toString();
	}
	
	
	
	public static String toString(Object object){
		if(object == null){
			return null;
		}
		return object.toString();
	}
	
	
}
